<template>
  <div>
    <el-tree
      ref="buttonTree"
      :data="buttonTreeData"
      :default-checked-keys="buttonTreeIds"
      :props="buttonDefaultProps"
      default-expand-all
      highlight-current
      node-key="onlyId"
      show-checkbox
      @check="nodeChange"
    />
  </div>
</template>
<script>
import { getAllButtons, addButtonAuthority, getButtonByAutorityId } from '@/api/sysButton'
export default {
  name: 'Buttons',
  props: {
    row: {
      default: function() {
        return {}
      },
      type: Object
    }
  },
  data() {
    return {
      buttonTreeData: [],
      buttonTreeIds: [],
      needConfirm: false,
      buttonDefaultProps: {
        children: 'children',
        label: 'cname'
      }
    }
  },
  async created() {
    // 获取button并整理成树结构
    const res2 = await getAllButtons({ parentId: this.row.parentId })
    const buttons = res2.data.buttons

    this.buttonTreeData = this.buildButtonTree(buttons)
    const res = await getButtonByAutorityId({
      authorityId: this.row.authorityId
    })
    this.activeUserId = this.row.authorityId
    this.buttonTreeIds = []
    res.data.buttons && res.data.buttons.map(item => {
      this.buttonTreeIds.push(item.ID)
    })
  },
  methods: {
    nodeChange() {
      this.needConfirm = true
    },
    // 暴露给外层使用的切换拦截统一方法
    enterAndNext() {
      this.authButtonEnter()
    },
    // 创建button树方法
    buildButtonTree(buttons) {
      const buttonObj = {}
      buttons && buttons.map(item => {
        item.onlyId = item.ID
        if (item.buttonGroup in buttonObj) {
          buttonObj[item.buttonGroup].push(item)
        } else {
          Object.assign(buttonObj, { [item.buttonGroup]: [item] })
        }
      })
      const buttonTree = []
      for (const key in buttonObj) {
        const treeNode = {
          ID: key,
          cname: buttonObj[key][0].menu.title,
          children: buttonObj[key]
        }
        buttonTree.push(treeNode)
      }
      return buttonTree
    },
    // 关联关系确定
    async authButtonEnter() {
      const checkArr = this.$refs.buttonTree.getCheckedNodes(true)
      var buttonInfos = []
      checkArr && checkArr.map(item => {
        buttonInfos.push(item)
      })
      const res = await addButtonAuthority({
        authorityId: this.activeUserId,
        buttons: buttonInfos
      })
      if (res.code === 0) {
        this.$notify({
          type: 'success',
          title: '成功',
          message: 'button设置成功'
        })
      }
    }
  }
}
</script>
<style lang="scss">
</style>
